//
//  YHYExpandViewController.m
//  Home
//
//  Created by 杨泓晔 on 16/7/1.
//  Copyright © 2016年 LanJue. All rights reserved.
//new

#import "YHYExpandViewController.h"
#import "YHYExpandTableViewCell.h"
#import "YHYCompanyAddPictureCell.h"
#import "TZImagePickerController.h"
#import "YHYButtonTableViewCell.h"
#import "WSHeaderActView.h"
@interface YHYExpandViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,TZImagePickerControllerDelegate,YHYCompanyAddPicturedelegate,YHYButtonTableViewdelegate,WSHeaderActViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (strong, nonatomic) IBOutlet UIImageView *HeadImageView;
//@property (strong, nonatomic) IBOutlet UITextField *companyTextField;
//@property (strong, nonatomic) IBOutlet UITextField *rangeTextField;
//@property (strong, nonatomic) IBOutlet UITextField *httpTextField;
@property (strong, nonatomic) IBOutlet UIButton *saveButton;
@property (nonatomic,strong) UITableView *myTableView;
@property (nonatomic,strong) UILabel *logoL;
@property (nonatomic,retain) NSArray *array;
@property (nonatomic, assign) NSInteger numOfContent;
@property (nonatomic, strong)NSString *pwdTextField;
@property (nonatomic,strong) UILabel *addPic;
@property (nonatomic, strong) WSHeaderActView *headerAV;


@end

@implementation YHYExpandViewController


-(void) viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    
}

-(void) viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
    self.tabBarController.tabBar.hidden=NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = LV;
    // Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(Back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    [self creatView];
    _array = @[@"公司名称",@"公司介绍",@"经营范围"];
    self.selectedPhotos = [NSMutableArray array];
    _addPic = [UILabel new];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
                                                 name:@"UITextFieldTextDidChangeNotification" object:_pwdTextField];
    
}

- (void)creatView{
    
    
  
    
    
    
    
    
    UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200 * AUTO_HEIGHT)];

    
    
    
    
    _HeadImageView = [UIImageView new];
    _HeadImageView.backgroundColor = LV;
    //添加边框
    [headV addSubview:_HeadImageView];
    CALayer * layer = [_HeadImageView layer];
    layer.borderColor = KH.CGColor;
    layer.borderWidth = 0.5f;
    [_HeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
//        make.top.mas_equalTo(177/3 * AUTO_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(100 * AUTO_WIDTH, 100 * AUTO_HEIGHT));
        make.centerXWithinMargins.mas_equalTo(headV);
        make.bottom.mas_equalTo(headV.mas_bottom).offset(-40 * AUTO_HEIGHT);
    }];
    _HeadImageView.backgroundColor = LV;
    CALayer *la = [_HeadImageView layer];
    
    la.borderColor = [[UIColor colorWithWhite:0.667 alpha:0.840]CGColor];
    la.borderWidth = 1.2;
    _HeadImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapV = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(HeaderImageVTap:)];
    [_HeadImageView addGestureRecognizer:tapV];
    
    
    
    
    
    _logoL = [UILabel new];
    [_HeadImageView addSubview:_logoL];
    [_logoL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(60/3 * AUTO_HEIGHT);
        make.left.mas_equalTo(_HeadImageView);
        make.width.mas_equalTo(_HeadImageView);
        make.bottom.mas_equalTo(_HeadImageView.mas_bottom);
        
    }];
    _logoL.backgroundColor = [UIColor lightGrayColor];
    _logoL.text = @"公司Logo";
    _logoL.textColor = [UIColor whiteColor];
    _logoL.textAlignment = NSTextAlignmentCenter;
    _logoL.font = [UIFont fontWithName:TFont size:TEXTLABELFONT];
    

    
    
    _myTableView = [UITableView new];
    [self.view addSubview:_myTableView];
    [_myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(self.view);
        make.left.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view);
        
    }];
    
    _myTableView.tableHeaderView = headV;
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.backgroundColor = LV;
    _myTableView.separatorStyle = NO;
    [_myTableView registerClass:[YHYExpandTableViewCell class] forCellReuseIdentifier:@"YHYExpandTableViewCell"];
    [_myTableView registerClass:[YHYCompanyAddPictureCell class] forCellReuseIdentifier:@"YHYCompanyAddPictureCell"];
    [_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableViewcell"];
    [_myTableView registerClass:[YHYButtonTableViewCell class] forCellReuseIdentifier:@"YHYButtonTableViewCell"];
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapAction:)];
//    [self.myTableView addGestureRecognizer:tap];

    
    
}
-(void)HeaderImageVTap:(UITapGestureRecognizer *)imageShows{


     [self.headerAV show];


}
#pragma mark - 头像点击View
- (WSHeaderActView *)headerAV {
    
    if (!_headerAV) {
        self.headerAV = [[WSHeaderActView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.headerAV.delegate = self;
        [self.view addSubview:_headerAV];
    }
    
    return _headerAV;
}
#pragma mark - headerAV 点击事件代理
- (void)presentImagePicker:(OPENIMAGE)img {
    
    if (img == 0) {
        [self selectCamera];
    } else if (img == 1) {
        [self selectPics];
    } else {
        
        
    }
}
- (void)selectCamera {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
}

- (void)selectPics {
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;

    [self presentViewController:imagePicker animated:YES completion:nil];
}
// 选中照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    _HeadImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
    _logoL.hidden = YES;
    [self.myTableView reloadData];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 8;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 3) {
        if (_selectedPhotos.count != 0) {
            return _selectedPhotos.count;
        }
        else{
        return 0;
        }
        
    }
    else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YHYExpandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHYExpandTableViewCell"];
    cell.backgroundColor = LV;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.companyTextField.delegate = self;
    if (indexPath.section == 0) {
        cell.company.text = @"公司简称";
        cell.companyTextField.text = _pwdTextField;
        cell.companyTextField.tag = 1000;
        cell.companyTextField.delegate = self;

    }
    if (indexPath.section == 1) {
        cell.company.text = @"公司介绍";
         cell.companyTextField.tag = 1001;
        cell.companyTextField.text = _pwdTextField;
    }
    if (indexPath.section == 2) {
        cell.company.text = @"经营范围";
        cell.companyTextField.tag = 1002;
        cell.companyTextField.text = _pwdTextField;

    }
    if (indexPath.section == 3) {
        YHYCompanyAddPictureCell *ce = [tableView dequeueReusableCellWithIdentifier:@"YHYCompanyAddPictureCell"];
        ce.myImageView.image = _selectedPhotos[indexPath.row];
        ce.delegate = self;
        return ce;

    }
    if (indexPath.section == 4) {
        UITableViewCell  *addCell = [tableView dequeueReusableCellWithIdentifier:@"tableViewcell"];
        addCell.selectionStyle = UITableViewCellSelectionStyleNone;
        addCell.backgroundColor = LV;
        [addCell addSubview:_addPic];
        [_addPic mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(addCell.mas_top).offset(10 * AUTO_HEIGHT);
            make.width.mas_equalTo(200 * AUTO_WIDTH);
            make.height.left.mas_equalTo(15 * AUTO_HEIGHT);
            
            
        }];
        _addPic.text = @"添加公司图片";
        _addPic.font = [UIFont fontWithName:@"Arial" size:TEXTCONTENTFONT];
        _addPic.textColor = ZI;
        
        
        UIImageView *imageV = [UIImageView new];
        [addCell addSubview:imageV];
        [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.width.mas_equalTo(addCell);
            make.bottom.mas_equalTo(addCell);
            make.top.mas_equalTo(_addPic.mas_bottom).offset(10 * AUTO_HEIGHT);
            
        }];
        imageV.image = [UIImage imageNamed:@"1080x240"];
        return addCell;
    }
    if (indexPath.section == 5) {
        cell.company.text = @"公司地址";
         cell.companyTextField.tag = 1004;
        cell.companyTextField.text = _pwdTextField;

    }
    if (indexPath.section == 6) {
        cell.company.text = @"公司官网（选填）";
         cell.companyTextField.tag = 1005;
        cell.companyTextField.text = _pwdTextField;

    }
    
    if (indexPath.section == 7) {
        YHYButtonTableViewCell *cebu = [tableView dequeueReusableCellWithIdentifier:@"YHYButtonTableViewCell"];
        [cebu.button setTitle:@"保存" forState:UIControlStateNormal];
        cebu.selectionStyle = UITableViewCellSelectionStyleNone;
        cebu.delegate = self;
        return cebu;
    }
       return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 4) {
        [self pickPhotoButtonClick:nil];
    }
    else{
        [self resignFirstResponder];
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section != 3) {
        
        if (indexPath.section == 4) {
            return 120 * AUTO_HEIGHT;
        }
    return 100 * AUTO_HEIGHT;
    }
    else{
        return 900/3 * AUTO_HEIGHT;
    }
}


#pragma mark - Notification Method
-(void)textFiledEditChanged:(NSNotification *)obj
{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > _numOfContent)
            {
                textField.text = [toBeString substringToIndex:_numOfContent];
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > _numOfContent)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_numOfContent];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:_numOfContent];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _numOfContent)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    textField.keyboardType = UIKeyboardTypeDefault;
    [UIView animateWithDuration:.7f delay:0.f usingSpringWithDamping:.7f initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    } completion:nil];
    
    if (textField.tag == 1000) {
        //        [UIView animateWithDuration:.3f animations:^{
        //            self.view.frame = CGRectMake(0, -  * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
        //
         _numOfContent = 10;
        //        }];
    }
    if (textField.tag == 1001) {
        _numOfContent = 19;//公司介绍
        [UIView animateWithDuration:.3f animations:^{
            self.view.frame = CGRectMake(0, - 50 * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
            
        }];
        
    }
    if (textField.tag == 1002) {
        _numOfContent = 19;//经营范围30
        [UIView animateWithDuration:.3f animations:^{
            self.view.frame = CGRectMake(0, - 167 * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
            
        }];
        
    }
    
    if (textField.tag == 1003) {
         _numOfContent = 9;
        [UIView animateWithDuration:.3f animations:^{
            self.view.frame = CGRectMake(0, -200 * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
            
        }];
        
    }
    if (textField.tag == 1004) {
         _numOfContent = 24;//公司地址
        [UIView animateWithDuration:.3f animations:^{
            self.view.frame = CGRectMake(0, -200 * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
            
        }];
        
    }
    if (textField.tag == 1005) {
         _numOfContent = 19;//公司官网
        [UIView animateWithDuration:.3f animations:^{
            self.view.frame = CGRectMake(0, -200 * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
            
        }];
        
    }



    
    
    return YES;
}


-(void) textFieldDidChanged:(UITextField *) textField
{
    NSString *toBeString=textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange=[textField markedTextRange];
    UITextPosition  *position=[textField positionFromPosition:selectedRange.start offset:0];
    
    //没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position) {
        
        //编写正则表达式：只能是数字或英文，或两者都存在
        NSString *regex=@"^[\u4E00-\u9FA5]+$";
        
        //创建谓词对象设定条件的表达式
        NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF MATCHES%@",regex];
        
        NSMutableString *muStr=[[NSMutableString alloc]initWithString:toBeString];
        NSMutableArray *ranges=[[NSMutableArray alloc]init];
        for (int i=0; i<toBeString.length; i++) {
            
            NSString *str=[toBeString substringWithRange:NSMakeRange(i, 1)];
            
            //对字符串进行判断
            if (![predicate evaluateWithObject:str]) {
                
                if (![ranges containsObject:str]) {
                    [ranges addObject:str];
                }
            }
        }
        for (NSString *string in ranges) {
            [muStr  replaceOccurrencesOfString:string withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, muStr.length)];
        }
        if (muStr.length >10) {
            
            NSRange rangelndex=[muStr rangeOfComposedCharacterSequenceAtIndex:10];
            
            if (rangelndex.length ==1) {
                textField.text=[muStr substringToIndex:10];
            }else{
                
                NSRange  rangeRange=[muStr rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 10)];
                textField.text=[muStr substringWithRange:rangeRange];
            }
        }
        else{
            
            textField.text=muStr;
        }
    }
}
- (void)TapAction:(UITapGestureRecognizer *)tap{
    //    [commentText resignFirstResponder];
    
    
//    [self resignFirstResponder];
////    [self resignFirstResponder];
////    [self resignFirstResponder];
//    
//    [UIView animateWithDuration:0.20f animations:^{
//        
//        
//        self.view.frame =CGRectMake(0, 0 * AUTO_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT);
//        [_HeadImageView mas_updateConstraints:^(MASConstraintMaker *make) {
//            
//            make.top.mas_equalTo(177/3* AUTO_HEIGHT + 64 * AUTO_HEIGHT);
//            make.size.mas_equalTo(CGSizeMake(100 * AUTO_WIDTH, 100 * AUTO_HEIGHT));
//            make.centerXWithinMargins.mas_equalTo(self.view);
//        }];
//        
//    }];
//    
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
    [UIView animateWithDuration:0.20f animations:^{
        
        
        self.view.frame =CGRectMake(0, 64 * AUTO_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT);
//        [_HeadImageView mas_updateConstraints:^(MASConstraintMaker *make) {
//            
//            make.top.mas_equalTo(177/3* AUTO_HEIGHT + 64 * AUTO_HEIGHT);
//            make.size.mas_equalTo(CGSizeMake(100 * AUTO_WIDTH, 100 * AUTO_HEIGHT));
//            make.centerXWithinMargins.mas_equalTo(self.view);
//        }];
        
    }];
    
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text == self.pwdTextField) {
        if (self.pwdTextField.length > _numOfContent) {
            
            if (textField.text.length > _numOfContent){
                
                return NO;
            }
        }
        
    }
    
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    //允许移动
    return YES;
    //return NO;
}

//通知响应方法
- (void)change:(NSNotification *)notification
{
    NSMutableArray *ar = [notification object];
    self.selectedPhotos = ar;
    NSLog(@"qqqq%@",ar);
    [_myTableView reloadData];
    
}

- (IBAction)pickPhotoButtonClick:(UIButton *)sender {
    NSInteger mum = 9;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:mum selectArr:_selectedPhotos delegate:self];
    imagePickerVc.selectCount = _selectedPhotos.count;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    [_myTableView reloadData];
    
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    [_selectedPhotos addObjectsFromArray:photos];
    //  NSLog(@"wwww%ld",(unsigned long)photos.count);
    //[self configCollectionView];
    
//    _myCollectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    
//    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    //   [self changeUICollectionView];
    [_myTableView reloadData];
//    [_myCollectionView reloadData];
    
    
}




//返回按钮
-(void) Back:(UIButton *) btn
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 协议
- (void)buttonAction:(UIButton *)button{
    YHYCompanyAddPictureCell *cell = (YHYCompanyAddPictureCell *)button.superview.superview;
    NSIndexPath *indexPath = [_myTableView indexPathForCell:cell];
    
    if (1001 == button.tag) {
        // 上
        
        
        if (0 == indexPath.row) {
            NSLog(@"到顶了");
        } else {
            [_selectedPhotos exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row - 1];
            
            //            NSArray *arr = @[
            //                             [NSIndexPath indexPathForItem:indexPath.row inSection:0],
            //                             [NSIndexPath indexPathForItem:indexPath.row - 1 inSection:0]];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:3]] withRowAnimation:UITableViewRowAnimationTop];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row - 1 inSection:3]] withRowAnimation:UITableViewRowAnimationTop];
        }
        
        
    }
    
    if (1002 == button.tag) {
        if (_selectedPhotos.count- 1 == indexPath.row) {
            NSLog(@"到底部");
        }
        else{
            [_selectedPhotos exchangeObjectAtIndex:indexPath.row  withObjectAtIndex:indexPath.row + 1 ];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row + 1 inSection:3]] withRowAnimation:UITableViewRowAnimationTop];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:3]] withRowAnimation:UITableViewRowAnimationTop];
        }
    }
    
    if (1000 == button.tag) {
        
        [_selectedPhotos removeObjectAtIndex:indexPath.row];
        [_myTableView reloadData];
    }
    
}
- (void)presentDelegate{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
